'use strict';
/**
 * 黄总--model类
 *2017.3.17
 */
export default class extends think.Model {
	
	/*
	**新增项目分类
	**输入：data=>{},
	**返回类型：return=>{success:1,info:'成功or失败'}
	*/
	async add(data){
		let is_exist = await this.model('or_subjectcategory').where({name:data.name,departmentid:data.departmentid}).find();
		if(!think.isEmpty(is_exist)){
			return {success:0,info:"此项目分类已经存在！"};
		}
		//写入数据库
		let res = await this.model('or_subjectcategory').add(data);
		return res?{success:1,info:"添加成功！"}:{success:0,info:"添加失败！"};
	}


	/*
	**编辑项目分类
	**输入：data=>{},
	**返回类型：return=>{success:1,info:'成功or失败'}
	*/
	async update(data){
		//如果id不存在报错
		if(!data.id){
			return {success:0,info:"传值错误！"};
		};
		let is_exist = await this.model('or_subjectcategory').where({name:data.name,departmentid:data.departmentid,id:['!=',data.id]}).find();
		if(!think.isEmpty(is_exist)){
			return {success:0,info:"此项目分类已经存在！"};
		}
		//写入
		let res = await this.model('or_subjectcategory').where({id:data.id}).update(data);
		return res?{success:1,info:"编辑成功！"}:{success:0,info:"编辑失败！"};
	}

	/*
	**查找单个项目分类
	**输入：id,
	**返回类型：return=>subjectcategory
	*/
	async find(id){
		let info = await this.model('or_subjectcategory').where({id:id}).find();
		return info;
	}

	/*
	**输出项目分类列表
	**输入：机构的id
	**返回类型：{}
	*/
	async list(departmentid){
		//取出项目分类数据
		let list = await this.model('or_subjectcategory')
			.alias('ob')
			.field('ob.*,oo.name as pname')
			.join('think_or_subjectcategory oo on ob.pid=oo.id')
			.where({'ob.departmentid':departmentid})
			.select();
		return list;
	}

	/*
	**删除单个项目分类
	**输入：项目分类id
	**返回类型：{}
	*/
	async delete(id){
		//判断是否能被删除
		let is_child = await this.model('or_subjectcategory').where({pid:id}).find();
		if(!think.isEmpty(is_child)){
			return {success:0,info:"请先删除该分类下子分类！"};
		};
		let res = await this.model('or_subjectcategory').where({id:id}).delete();
		return res?{success:1,info:"删除成功！"}:{success:0,info:"删除失败！"};
	}
}